<?php

namespace Beerus\Modules\Brand\Controllers;

use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Layout\Row;
use Encore\Admin\Widgets\Tab;
use Illuminate\Http\Request;
use Biz\model\brandDecoration\BrandCard;
use Biz\model\brandDecoration\BrandCardListing;
use Biz\model\brand\Brand;
use Doraemon\tools\ImgUrl;
use Doraemon\cache\Queue;
use Biz\service\BrandIndex;
use Biz\model\brandIndex\BrandMsg;


class H5CheckController extends Controller
{
    const PAGE_SIZE = 20;
    const DEFAULT_HAOHAOZHU_UID = 11941;

    public function __construct()
    {
        parent::__construct();
        Admin::script('$(".pjax-container").attr("id","pjax-container");');
    }

    public function index(Request $request, Content $content)
    {
        $params = $request->all();

        if(!isset($params['check_status'])) {
            $params['check_status'] = 0;
            $request->merge([
                'check_status' => '0'
            ]);
        }

        if(!isset($params['per_page'])) {
            $params['per_page'] = 20;
        }
        if(!isset($params['page'])) {
            $params['page'] = 1;
        }
        if(isset($params['brand_name']) && $params['brand_name']) {
            $brand_id = Brand::getBrandIdByName($params['brand_name']);
            $params['brand_id'] = $brand_id;
            $where['brand_id'] = $params['brand_id'];
        }
        if(isset($params['brand_id']) && $params['brand_id']) {
            $where['brand_id'] = $params['brand_id'];
        }
        $where['check_status'] = $params['check_status'];
        $start = ($params['page'] - 1) * $params['per_page'];
        $where['li_status[!]'] = BrandCardListing::DELETE_STATUS;
        $card_list = BrandCardListing::getInfosByWhere($where, $start, $params['per_page']);

        if($card_list && is_array($card_list)) {
            $brand_ids = array_unique(array_filter(array_column($card_list, 'brand_id')));
            $brand_infos = Brand::getInfoByIds($brand_ids);
            $brand_infos_arr = [];
            if($brand_infos && is_array($brand_infos)) {
                foreach($brand_infos as $brand_info) {
                    $brand_infos_arr[$brand_info['id']] = $brand_info;
                }
            }
            foreach($card_list as &$card_info) {
                $card_info['brand_info'] = $brand_infos_arr[$card_info['brand_id']];
                $card_info['brand_info']['brand_identify'] = Brand::BRAND_TYPE[$brand_infos_arr[$card_info['brand_id']]['brand_type']];
            }
        }

        $count = BrandCardListing::getInfosCount($where);
        $options = [
            'perPage' => $params['per_page'] ? : 20,
        ];

        $gridModel = new pGridDataModel($card_list, $count, $options);

        $listGrid = Admin::grid($gridModel, function (Grid $grid) {

            $grid->disableExport();
            $grid->disableRowSelector();
            $grid->disableCreateButton();
            $grid->expandFilter();
            //$grid->disableActions();

            $grid->filter(function (Grid\Filter $filter) {
                $filter->disableIdFilter();
                $filter->column(1 / 2, function ($filter) {
                    $filter->dropDown('search_keyword', [
                        'brand_id' => '品牌id',
                        'brand_name' => '品牌名称'
                    ]);
                });
                $filter->column(1 / 2, function ($filter) {
                    $filter->equal('check_status', '审核状态')->radio([
                        0 => '待审核',
                        1 => '审核通过',
                        2 => '审核未通过'
                    ])->default(0);
                });
            });
            $grid->column('id', 'banner_id');
            $grid->column('brand_id', '品牌id');
            $grid->column('brand_info', '品牌信息')->display(function() {
                return "品牌名称：".$this->brand_info['brand_name']."<br>品牌身份：".$this->brand_info['brand_identify']."<br><img src='".ImgUrl::getUrl(ImgUrl::APPTYPE_BIZ, $this->brand_info['logo'], ImgUrl::IMAGE_SIZE_SQ_PHONE)."' width='100' />";
            });
            $grid->column('link_type', '活动类型')->display(function() {
                return "站外活动";
            })->width(100);
            $grid->column('pic_id', '活动图片')->display(function() {
                return "<img src='".ImgUrl::getUrl(ImgUrl::APPTYPE_BIZ, $this->pic_id, ImgUrl::IMAGE_SIZE_ORI_NPHONE)."' width=200 /><br>添加时间：".$this->addtime."<br>最后修改时间：".$this->edittime;
            })->width(250);
            $grid->column('link_module', '活动所属平台')->replace(BrandCardListing::LINK_MODULE)->width(100);
            $grid->column('link_params', '活动链接')->display(function() {
                return "<a href='".$this->link_params."' target='_blank'>点击跳转</a>";
            })->width(100);
            $grid->column('check_status', '审核状态')->replace(BrandCardListing::CHECK_STATUS);

            $grid->actions(function (Grid\Displayers\Actions $actions){
                $actions->disableEdit();
                $actions->disableView();
                $actions->disableDelete();
                if($actions->row->check_status == BrandCardListing::CHECK_STATUS_OVER) {
                    $actions->prepend('<br><a class="fa reload-data fa-check check-pass" href="javascript:;" data-id="'.$actions->row->id.'" data-brandid="'.$actions->row->brand_id.'"  data-link="'.$actions->row->link_params.'" data-pic="'.$actions->row->pic_id.'">审核通过</a>');
                } else if($actions->row->check_status == BrandCardListing::CHECK_STATUS_PASS) {
                    $actions->prepend('<br><a class="fa fa-close reload-data check-over" href="javascript:;" data-id="'.$actions->row->id.'" data-brandid="'.$actions->row->brand_id.'"  data-link="'.$actions->row->link_params.'" data-pic="'.$actions->row->pic_id.'">审核不通过</a><br><br><br>');
                } else {
                    $actions->prepend('<br><a class="fa reload-data fa-check check-pass" href="javascript:;" data-id="'.$actions->row->id.'" data-brandid="'.$actions->row->brand_id.'"  data-link="'.$actions->row->link_params.'" data-pic="'.$actions->row->pic_id.'">审核通过</a>');
                    $actions->prepend('<br><a class="fa fa-close reload-data check-over" href="javascript:;" data-id="'.$actions->row->id.'" data-brandid="'.$actions->row->brand_id.'"  data-link="'.$actions->row->link_params.'" data-pic="'.$actions->row->pic_id.'">审核不通过</a><br><br><br>');
                }
            });

        });

        Admin::script($this->checkPop());

        return $content
            ->header('品牌活动审核')
            ->body($listGrid);

    }

    //审核弹窗
    public function checkPop()
    {
        return <<<SCRIPT
            //审核通过
            $('.check-pass').unbind('click').click(function() {
                var id = $(this).data('id');
                var brand_id = $(this).data('brandid');
                var link = $(this).data('link');
                var pic_id = $(this).data('pic');
                swal({
                    title: "确认要将这个站外活动链接标记通过嘛？",
                    type: "warning",
                    showCancelButton: true,
                    confirmButtonColor: "#DD6B55",
                    confirmButtonText: "确认通过",
                    showLoaderOnConfirm: true,
                    cancelButtonText: "取消",
                    preConfirm: function() {
                        $.post('checkpass', {'id':id, 'brand_id':brand_id, 'link':link, 'pic_id':pic_id}, function (data) {
                            $.pjax.reload('#pjax-container');
                            if(data.code == 1) {
                                swal(data.msg, '', 'success');
                            } else {
                                swal(data.msg, '', 'error');
                            }
                        });
                       
                    }
                });
            });
            
            //审核不通过
            $('.check-over').unbind('click').click(function() {
                var id = $(this).data('id');
                var brand_id = $(this).data('brandid');
                var link = $(this).data('link');
                var pic_id = $(this).data('pic');
                
                layer.prompt({title:'输入不通过理由，此理由会发送给用户哦', formType: 2}, function(pass, index){
                     
                    //layer.msg('演示完毕！您的口令：'+ pass);
                    swal({
                        title: "确认要将这个站外活动链接标记 不通过 嘛？标记不通过后此banner将在app中不展示",
                        type: "warning",
                        showCancelButton: true,
                        confirmButtonColor: "#DD6B55",
                        confirmButtonText: "确认标记不通过",
                        cancelButtonText: "取消",
                        preConfirm: function() {
                            $.post('checkover', {'id':id, 'pass':pass, 'brand_id':brand_id, 'link':link, 'pic_id':pic_id}, function (data) {
                                $.pjax.reload('#pjax-container');
                                if(data.code == 1) {
                                    swal(data.msg, '', 'success');
                                } else {
                                    swal(data.msg, '', 'error');
                                }
                            }); 
                        }
                    });
                    layer.close(index);
                });
               
            });
SCRIPT;
    }

    //审核通过
    public function checkPass(Request $request)
    {
        $request = $request->all();
        $id = $request['id'];
        $brand_id = $request['brand_id'];
        $uid = Brand::getInfoByIds([$brand_id])[0]['uid'];
        $link = $request['link'];
        $pic_id = $request['pic_id'];
        $rs = BrandCardListing::editData([
            "edittime" => date('Y-m-d H:i:s', time()),
            'check_status' => BrandCardListing::CHECK_STATUS_PASS,
            'li_status' => BrandCardListing::NORMAL_STATUS
        ], [
            'id' => $id
        ]);
        if($uid) {
            Queue::insertQueue('queue/Sysmsg/Send' ,
                [
                    'msgCode' => 0,
                    'to_uid' => $uid,
                    'msgParams' => [
                        'from_uid'=> self::DEFAULT_HAOHAOZHU_UID,
                        'title'=>'',
                        'img'=>'',
                        'link'=>'',
                        'detail'=>"你设置的跳转链接已审核通过并生效。链接地址：".$link
                    ]
                ], Queue::QUEUE_DORAEMON
            );
        }


        if($rs) {
            BrandIndex::writeMsg($brand_id, BrandMsg::MSG_TYPE_PASS, BrandMsg::MSG_SOURCE_H5, "你设置的跳转链接已审核通过并生效。链接地址：".$link);
            return [
                'code' => 1,
                'msg' => '审核通过成功'
            ];
        }
        return [
            'code' => 0,
            'msg' => '审核通过失败'
        ];
    }

    //审核不通过
    public function checkOver(Request $request)
    {
        $request = $request->all();
        $id = $request['id'];
        $brand_id = $request['brand_id'];
        $link = $request['link'];
        $msg = $request['pass'];
        $pic_id = $request['pic_id'];
        $uid = Brand::getInfoByIds([$brand_id])[0]['uid'];
        $rs = BrandCardListing::editData([
            "edittime" => date('Y-m-d H:i:s', time()),
            'check_status' => BrandCardListing::CHECK_STATUS_OVER,
            'li_status' => BrandCardListing::OVER_STATUS
        ], [
            'id' => $id
        ]);
        if($uid) {
            Queue::insertQueue('queue/Sysmsg/Send' ,
                [
                    'msgCode' => 0,
                    'to_uid' => $uid,
                    'msgParams' => [
                        'from_uid'=> self::DEFAULT_HAOHAOZHU_UID,
                        'title'=>'',
                        'img'=>'',
                        'link'=>'',
                        'detail'=>"你设置的跳转链接未通过审核，原因：「".$msg."」。链接地址：".$link
                    ]
                ], Queue::QUEUE_DORAEMON
            );
        }

        if($rs) {

            BrandIndex::writeMsg($brand_id, BrandMsg::MSG_TYPE_OVER, BrandMsg::MSG_SOURCE_H5, "你设置的跳转链接未通过审核，原因：「".$msg."」。链接地址：".$link);

            return [
                'code' => 1,
                'msg' => '审核不通过成功'
            ];
        }
        return [
            'code' => 0,
            'msg' => '审核不通过失败'
        ];
    }

}
